package com.victor9ac.mashup.threadpool;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import com.victor9ac.mashup.api.MashupDataType;
import com.victor9ac.mashup.elasticsearch.tasks.ElasticSearchOperation;
import com.victor9ac.mashup.threadpool.exception.MashupThreadPoolTimeoutException;


public class MashupThreadPool {

	ExecutorService threadPool;
	long threadPoolTimeout;
	int threadPoolSize;

	public MashupThreadPool(long threadPoolTimeout, int threadPoolSize) {
		this.threadPoolTimeout = threadPoolTimeout;
		this.threadPoolSize = threadPoolSize;
		threadPool = Executors.newFixedThreadPool(threadPoolSize);
	}

	public <T> T getResult(Future<T> futureTask)
			throws MashupThreadPoolTimeoutException {
		T res = null;
		try {
			res = futureTask.get(threadPoolTimeout, TimeUnit.MILLISECONDS);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TimeoutException e) {
			e.printStackTrace();
			throw new MashupThreadPoolTimeoutException(
					"Mashup WS is responding too slow", e);

		}
		return res;
	}


	public void run(ElasticSearchOperation elasticSearchOperation,	MashupDataType mashupDataType, String indexName, Object obj) {
		
		MashupElasticSearchTask task = new MashupElasticSearchTask(elasticSearchOperation, mashupDataType,indexName, obj);

		threadPool.submit(task);
	}

}
